package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;

	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;
	/**
	 * 根据用户id查询用户是否购买专辑或者声音
	 * @param userId
	 * @param albumId
	 * @param trackIdList
	 * @return  返回一个map，key是声音ID，value是0/1表示是否购买过
	 */
	@Override
	public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> trackIdList) {
		//思路：先根据用户ID+专辑ID判断是否购买专辑
		LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<UserPaidAlbum>();
		wrapper.eq(UserPaidAlbum::getUserId,userId);
		wrapper.eq(UserPaidAlbum::getAlbumId, albumId);
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(wrapper);
		//2 如果用户购买过专辑，把专辑里面所有声音购买过 map的key声音id value是1
		if(userPaidAlbum != null) {
			Map<Long, Integer> map = new HashMap<>();
			trackIdList.forEach(trackId->{
				map.put(trackId,1);
			});
			return map;
		}else {
			//3 如果用户没有买过专辑，根据用户id + 声音id查询购买哪些声音  user_paid_track
			LambdaQueryWrapper<UserPaidTrack> wrapper02 = new LambdaQueryWrapper<>();
			wrapper02.eq(UserPaidTrack::getUserId, userId);
			// in (1,2,3)
			wrapper02.in(UserPaidTrack::getTrackId, trackIdList);
			List<UserPaidTrack> userPaidTrackList =
					userPaidTrackMapper.selectList(wrapper02);

			//	获取到用户购买声音Id 集合
			List<Long> userPaidTrackIdList = userPaidTrackList.stream()
					.map(UserPaidTrack::getTrackId)
					.collect(Collectors.toList());

			Map<Long, Integer> map = new HashMap<>();

			// 所有：[1,2,3,4,5]      trackIdList
			// 购买：[1,2,3]          userPaidTrackIdList
			//4 根据查询购买声音，和所有声音比较，如果购买过 map的key声音id value是1
			//                                 如果没有购买过 map的key声音id value是0
			trackIdList.forEach(trackId->{
				boolean contains = userPaidTrackIdList.contains(trackId);
				if(contains) { //包含，购买过
					//	用户已购买声音
					map.put(trackId,1);
				} else { //不包含
					map.put(trackId,0);
				}
			});
			return map;
		}
	}
}
